import java.util.Arrays;

public class MyPriorityQueue {
    int[] elem;
    int usedSize;

    public MyPriorityQueue() {
        elem = new int[10];
    }

    public void initElem(int[] array) {
        for(int i = 0;i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }
    public void creatHeap() {
        for(int parent = ((usedSize-1) - 1)/ 2; parent >= 0 ;parent --) {
            siftDown(parent,usedSize);
        }
    }
    private void siftDown(int parent, int len) {
        int child = parent*2 + 1;
        while(child < len) {
            //确保右孩子不越界
            if(child + 1 < len && elem[child] < elem[child + 1]) {
                child = child+1;
            }
            //到这里确保child 是最大的孩子
            if(elem[child] > parent) {
                swap(child,parent);
                parent = child;
                child = parent*2+1;
            }else {
                //如果孩子没有跟大就直接结束
                break;
            }
        }
    }
    private void swap(int i ,int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }
    public void push(int val) {
        //查看空间是否足够，不够扩容
        if(emtpy()) {
            elem = Arrays.copyOf(elem,elem.length * 2);
        }
        //将val 放置队尾
        elem[usedSize] = val;
        //向上调整
        siftUp(usedSize);

        usedSize++;
    }

    private  void siftUp(int len) {
        int child = len;
        int perent = (child - 1) / 2;
        while(child > 0 && elem[child] > elem[perent]) {
            swap(child,perent);
            child = perent;
            perent = (child - 1) / 2;
        }
    }

    public boolean emtpy() {
        return usedSize == elem.length;
    }
    public int pop() {
        //判断是否为空
        if(usedSize == 0) {
            return -1;
        }
        //将最大的放到队尾
        int oldVal = elem[0];
        swap(0,usedSize -1);
        usedSize--;
        //这里已成功删除
        //接下来向下调整
        siftDown(0,usedSize);
        return oldVal;
    }




}
